import React, { useState, useEffect } from 'react'
import style from './login.module.scss'
import logo from '../../../images/logo.svg'
import { Link } from 'react-router-dom'
import validator from 'validator'
import { ILogin } from '../../../starter/model/interfaces'
import { useLazySignInQuery } from '../../../starter/api/authApi'
import { useActions } from '../../../starter/hooks/actions'

type TLogin = {

}
function Login({} : TLogin) {
  const [formData, setFormData] = useState<ILogin>({ email: '', password: '' })
  const [formErrors, setFormErrors] = useState<any>({ email: '', password: '' })
  const [isSubmitting, setIsSubmitting] = useState(false)
  const {setToken} = useActions()

  const isFormValid = () => {
    return (
      Object.values(formData).every((value) => value !== '') &&
      Object.values(formErrors).every((error) => error === '')
    )
  }
  const [login, {data, isLoading, isError, error}] = useLazySignInQuery()

  useEffect(() => {
    if (data) {
      setToken(data.token)
    }
  }, [data])
  const handleInputChange = (evt: React.ChangeEvent<HTMLInputElement>): void => {
    const { name, value } = evt.target
    setFormData({
      ...formData,
      [name]: value,
    })

    validateField(name, value)
  }

  const validateField = (fieldName: string, value: string) => {
    let errorMessage = ''

    switch (fieldName) {
      case 'email':
        if (value.length < 5) {
          errorMessage = 'Email должен содержать от 5 до 30 символов'
        } else if (!validator.isEmail(value)) {
          errorMessage = 'Введите корректный email'
        }
        break
      case 'password':
        if (!validator.isLength(value, { min: 5, max: 40 })) {
          errorMessage = 'Пароль должен содержать от 5 до 40 символов'
        }
        break
      default:
        break
    }

    setFormErrors({
      ...formErrors,
      [fieldName]: errorMessage,
    })
  }

  async function handleSubmit(evt: React.FormEvent<HTMLFormElement>): Promise<void> {
    evt.preventDefault()

    if (isFormValid() && !isSubmitting) {
      setIsSubmitting(true)
      try {
        login(formData)
      } catch (err) {
        console.log(err)
      } finally {
        setIsSubmitting(false)
      }
    }
  }

  return (
    <>
      <section className={style.login}>
        <img src={logo} alt='Логотип' className={style.login__logo} />
        <main className={style.login__content}>
          <h1 className={style.login__greeting}>Рады видеть!</h1>
          <form className={style.login__form} onSubmit={handleSubmit}>
            <label className={style.login__label}>
              E-mail
              <input
                className={style.login__input}
                name='email'
                type='email'
                placeholder='E-mail'
                minLength={5}
                maxLength={40}
                autoComplete='off'
                required
                value={formData.email}
                onChange={handleInputChange}
              />
              <span
                className={`${formErrors.email ? style['login__input-error'] : ''}`}
              >
                {formErrors.email}
              </span>
            </label>
            <label className={style.login__label}>
              Пароль
              <input
                className={style.login__input}
                name='password'
                type='password'
                placeholder='Пароль'
                minLength={5}
                maxLength={40}
                autoComplete='off'
                required
                value={formData.password}
                onChange={handleInputChange}
              />
              <span
                className={`${formErrors.password ? style['login__input-error'] : ''}`}
              >
                {formErrors.password}
              </span>
            </label>
            {isError && (
              <p className={style['login__error-message']}>{JSON.parse(JSON.stringify(error)).data.message}</p>
            )}
            <button
              className={`login__button ${
                !isFormValid() ? 'login__button_disabled' : ''
              }`}
              type='submit'
              disabled={!isFormValid() || isLoading}
            >
              Войти
            </button>
          </form>
          <p className={style.login__text}>
            Еще не зарегистрированы?{' '}
            <Link className={style.login__link} to='/signup'>
              <span className={style.login__signin}>Регистрация</span>
            </Link>
          </p>
        </main>
      </section>
    </>
  )
}

export default Login
